package com.kingdee.eas.custom.tiog.connector.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @author Jambin
 * @description httpClient 工具类
 * @copyright 天津金蝶软件有限公司
 * @date Created in 2020/3/24
 */

public class HttpClientUtil {

    // 编码格式。发送编码格式统一用UTF-8
    private static final String ENCODING = "UTF-8";

    // 设置连接超时时间，单位毫秒。
    private static final int CONNECT_TIMEOUT = 6000;

    // 请求获取数据的超时时间(即响应时间)，单位毫秒。
    private static final int SOCKET_TIMEOUT = 6000;

    /**
     * @param url 请求地址
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送get请求；不带请求头和请求参数
     * @title doGet
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doGet(String url) throws Exception {
        return doGet(url, null, null);
    }

    /**
     * @param url 请求地址
     * @param params 请求参数集合
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送get请求；带请求参数
     * @title doGet
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
        return doGet(url, null, params);
    }

    /**
     * @param url 请求地址
     * @param headers 请求头集合
     * @param params 请求参数集合
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送get请求；带请求头和请求参数
     * @title doGet
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params)
            throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建访问的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // 创建http对象
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // setConnectTimeout：设置连接超时时间，单位毫秒。
        // setConnectionRequestTimeout：设置从connect Manager (连接池) 获取Connection
        // 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
        // setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).build();
        httpGet.setConfig(requestConfig);

        // 设置请求头
        packageHeader(headers, httpGet);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse, httpClient, httpGet);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }

    /**
     * @param url 请求地址
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送post请求；不带请求头和请求参数
     * @title doPost
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doPost(String url) throws Exception {
        return doPost(url, null, null, null, null);
    }

    /**
     * @param url 请求地址
     * @param params 参数集合
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送post请求；带请求参数
     * @title doPost
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
        return doPost(url, null, params, null, null);
    }

    /**
     * @param url 请求地址
     * @param headers 请求头参数
     * @param params 参数集合
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送post请求；带请求参数和请求头
     * @title doPost
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params)
            throws Exception {
        return doPost(url, headers, params, null, null);
    }

    /**
     * @param url 请求地址
     * @param paramJson json格式参数
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送post请求；json格式参数
     * @title doPost
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doPost(String url, String paramJson) throws Exception {
        return doPost(url, null, null, paramJson, null);
    }

    /**
     * @param url 请求地址
     * @param headers 请求头参数
     * @param paramJson json格式参数
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送post请求；json格式参数,带请求头
     * @title doPost
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, String paramJson)
            throws Exception {
        return doPost(url, headers, null, paramJson, null);
    }

    /**
     * @param url 请求地址
     * @param headers 请求头参数
     * @param params 参数集合
     * @param fileLists 文件集合
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送post请求，带请求头，请求参数和文件
     * @title doPost
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers,
            Map<String, String> params, List<File> fileLists) throws Exception {
        return doPost(url, headers, params, null, fileLists);
    }

    /**
     * @param url 请求地址
     * @param headers 请求头参数
     * @param params 参数集合
     * @param paramJson json格式参数
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description post请求
     * @title doPost
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers,
            Map<String, String> params, String paramJson, List<File> fileLists) throws Exception {
        // 创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建http对象
        HttpPost httpPost = new HttpPost(url);

        // setConnectTimeout：设置连接超时时间，单位毫秒。
        // setConnectionRequestTimeout：设置从connect Manager(连接池)获取Connection
        // 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
        // setSocketTimeout：请求获取数据的超时时间(即响应时间)，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);

        // 设置请求头
        packageHeader(headers, httpPost);

        // 当文件不为空时，使用封装文件方法
        if (fileLists != null && !fileLists.isEmpty()) {
            packageFile(params, fileLists, httpPost);
        } else {
            // 封装请求参数
            packageParam(params, httpPost);
        }

        // 封装json参数
        packageJson(paramJson, httpPost);

        // 创建httpResponse对象
        CloseableHttpResponse httpResponse = null;

        try {
            // 执行请求并获得响应结果
            return getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            // 释放资源
            release(httpResponse, httpClient);
        }
    }

    /**
     * @param url 请求地址
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送put请求；不带请求参数
     * @title doPut
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doPut(String url) throws Exception {
        return doPut(url);
    }

    /**
     * @param url 请求地址
     * @param params 参数集合
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送put请求；带请求参数
     * @title doPut
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPut.setConfig(requestConfig);

        packageParam(params, httpPut);

        CloseableHttpResponse httpResponse = null;

        try {
            return getHttpClientResult(httpResponse, httpClient, httpPut);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * @param url 请求地址
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送delete请求；不带请求参数
     * @title doDelete
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doDelete(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).build();
        httpDelete.setConfig(requestConfig);

        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpResponse, httpClient, httpDelete);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * @param url 请求地址
     * @param params 参数集合
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 发送delete请求；带请求参数
     * @title doDelete
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
        if (params == null) {
            params = new HashMap<String, String>();
        }

        params.put("_method", "delete");
        return doPost(url, params);
    }

    /**
     * @param params 参数集合
     * @param httpMethod 请求方式
     * @return void
     * @description 封装请求头
     * @title packageHeader
     * @author Jambin
     * @date 2020/3/24
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封装请求头
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                // 设置到请求头到HttpRequestBase对象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * @param params 参数集合
     * @param httpMethod 请求方式
     * @return void
     * @description 封装请求参数
     * @title packageParam
     * @author Jambin
     * @date 2020/3/24
     */
    public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
            throws UnsupportedEncodingException {
        // 封装请求参数
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 设置到请求的http对象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
        }
    }

    /**
     * @param paramJson json格式参数
     * @param httpMethod 请求方式
     * @return void
     * @description 封装json参数
     * @title packageJson
     * @author Jambin
     * @date 2020/3/24
     */
    public static void packageJson(String paramJson, HttpEntityEnclosingRequestBase httpMethod) {
        if (paramJson != null && paramJson != "" && paramJson.length() != 0) {
            StringEntity entity = new StringEntity(paramJson, "UTF8");
            httpMethod.setEntity(entity);
        }
    }

    /**
     * @param params 参数集合
     * @param fileLists 文件集合
     * @param httpMethod 请求方式
     * @return void
     * @description 封装文件
     * @title packageFile
     * @author Jambin
     * @date 2020/3/24
     */
    public static void packageFile(Map<String, String> params, List<File> fileLists,
            HttpEntityEnclosingRequestBase httpMethod) {
        if (fileLists != null && !fileLists.isEmpty()) {
            MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
            for (String key : params.keySet()) {
                meBuilder.addPart(key, new StringBody(params.get(key), ContentType.TEXT_PLAIN));
            }
            for (File file : fileLists) {
                FileBody fileBody = new FileBody(file);
                meBuilder.addPart("file", fileBody);
            }
            HttpEntity reqEntity = meBuilder.build();
            httpMethod.setEntity(reqEntity);
        }
    }

    /**
     * @param httpResponse
     * @param httpClient
     * @param httpMethod
     * @return com.kingdee.eas.custom.tiog.connector.util.HttpClientResult
     * @description 执行http请求，获取响应结果
     * @title getHttpClientResult
     * @author Jambin
     * @date 2020/3/24
     */
    public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
            CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
        // 执行请求
        httpResponse = httpClient.execute(httpMethod);

        // 获取返回结果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {
            String content = "";
            InputStream inputStream = null;
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
                inputStream = bufferedEntity.getContent();
                content = EntityUtils.toString(bufferedEntity, ENCODING);
                System.out.println("contenttype:" + bufferedEntity.getContentType().getValue());
            }
            inputStream.close();
            return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content, inputStream);
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

    /**
     * @param httpResponse
     * @param httpClient
     * @return void
     * @description 释放资源
     * @title release
     * @author Jambin
     * @date 2020/3/24
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient)
            throws IOException {
        // 释放资源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }

}
